package lib

//link to 59
func init() {
	Probs = append(Probs, Problem{
		Num:         54,
		Discription: "螺旋矩阵",
		Level:       2,
		Labels: map[string]int{
			"矩阵": 1,
		},
	})
}

func SpiralOrder(matrix [][]int) []int {
	leftEdge := 0
	rightEdge := len(matrix[0]) - 1
	topEdge := 0
	bottomEdge := len(matrix) - 1
	k := 0
	length := len(matrix) * len(matrix[0])
	res := make([]int, length)

	for k < length {
		for j := leftEdge; j <= rightEdge && k < length; j++ {
			res[k] = matrix[topEdge][j]
			k++
		}
		topEdge++

		for i := topEdge; i <= bottomEdge && k < length; i++ {
			res[k] = matrix[i][rightEdge]
			k++
		}
		rightEdge--

		for j := rightEdge; j >= leftEdge && k < length; j-- {
			res[k] = matrix[bottomEdge][j]
			k++
		}
		bottomEdge--

		for i := bottomEdge; i >= topEdge && k < length; i-- {
			res[k] = matrix[i][leftEdge]
			k++
		}
		leftEdge++
	}

	return res
}
